package com.yanftch.json2ets

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.ui.DialogBuilder
import com.yanftch.json2ets.json2ets.FilePostfix
import com.yanftch.json2ets.json2ets.generator.GeneratorDelegateJava
import com.yanftch.json2ets.json2ets.generator.MessageDelegate
import com.yanftch.json2ets.json2ets.parser.typescript.ParseType
import com.yanftch.json2ets.json2ets.views.Json2TsForm
import com.yanftch.json2ets.json2ets.views.SetGetChooseDialog

class Json2etsAction : AnAction() {

    private val generatorDelegate = GeneratorDelegateJava(MessageDelegate())

    override fun actionPerformed(event: AnActionEvent) {
        DialogBuilder().apply {
            var fileName: String? = ""
            if (event.project == null) {
                fileName = null
            } else {
                val name = FileEditorManager.getInstance(event.project!!).selectedEditor?.file?.name ?: ""
                var split : List<String> = ArrayList()
                    if (name.endsWith(FilePostfix.ETS)) {
                        split = name.split(FilePostfix.ETS)
                    } else if (name.endsWith(FilePostfix.TS)) {
                        split = name.split(FilePostfix.TS)
                    }
                if (split.size == 2) {
                    fileName = split[0]
                }
            }
            val form = Json2TsForm(fileName).apply {
                setOnGenerateListener(object : Json2TsForm.OnGenerateClicked {
                    override fun onClicked(rootName: String, json: String, parseType: ParseType) {
                        var generateSetGet = false
                        if (ParseType.TSClass == parseType) {
                            val dialog = SetGetChooseDialog()
                            dialog.setOnButtonClickListener { isConfirm ->
                                // 生成 set()/get() 方法
                                generateSetGet = isConfirm
                            }
                            dialog.isVisible = true
                        } else {
                            generateSetGet = false
                        }
                        window.dispose()
                        generatorDelegate.runGeneration(event, json, rootName, parseType, generateSetGet)
                    }
                })
            }
            setCenterPanel(form.rootView)
            setTitle("Json2ets")
            removeAllActions()
            show()
        }
    }

    override fun update(e: AnActionEvent) {
        e.presentation.isEnabled = true
    }
}
